package com.zee.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zee.admin.annotation.LogOperation;
import com.zee.admin.entity.SysUser;
import com.zee.admin.model.dto.SysUserDTO;
import com.zee.admin.model.dto.SysUserPasswordDTO;
import com.zee.admin.model.dto.SysUserQueryDTO;
import com.zee.admin.model.excel.SysUserExcel;
import com.zee.admin.model.vo.SysUserVO;
import com.zee.admin.service.ISysRoleUserService;
import com.zee.admin.service.ISysUserService;
import com.zee.admin.shiro.AdminSecurityUser;
import com.zee.admin.shiro.AdminUserDetail;
import com.zee.common.model.response.CommonCode;
import com.zee.common.model.response.Result;
import com.zee.common.utils.ConvertUtil;
import com.zee.common.utils.EasyExcelRepeatWritePages;
import com.zee.common.utils.EasyExcelUtil;
import com.zee.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 用户管理
 *
 * @author Mark LinZee
 * @email LinZee666@163.com
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统用户管理")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleUserService sysRoleUserService;

    @PostMapping("page")
    @ApiOperation("分页列表")
    @RequiresPermissions("sys:user:page")
    public Result page(@Validated @RequestBody SysUserQueryDTO dto) {
        Page<SysUserVO> page = sysUserService.page(dto);
        return Result.ok(page);
    }

    @GetMapping("test")
    @ApiOperation(value = "test")
    public Result test() {

        HashMap<String, Object> map = new HashMap<>();
        List<SysUser> list = sysUserService.test(map);
        return Result.ok(list);
    }

    @GetMapping("info")
    @ApiOperation("用户信息")
    @RequiresPermissions("sys:user:info")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SysUserVO.class)
    })
    public Result info(@RequestParam Integer id) {
        SysUserVO data = sysUserService.getById(id);
        //用户角色列表
        List<Integer> roleIdList = sysRoleUserService.getRoleIdList(id);
        data.setRoleIdList(roleIdList);
        return Result.ok(data);
    }

    @GetMapping("loginUserInfo")
    @ApiOperation("当前管理员信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SysUserVO.class)
    })
    public Result loginUserInfo() {
        SysUserVO data = ConvertUtil.sourceToTarget(AdminSecurityUser.getUser(), SysUserVO.class);
        return Result.ok(data);
    }

    @PostMapping("updatePassword")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result updatePassword(@Validated @RequestBody SysUserPasswordDTO dto) {
        AdminUserDetail user = AdminSecurityUser.getUser();
        //原密码不正确
        if (!DigestUtils.sha256Hex(dto.getPassword()).equals(user.getPassword())) {
            return Result.error(CommonCode.ORIGINAL_PASSWORD_ERROR);
        }
        sysUserService.updatePassword(user.getId(), dto.getNewPassword());
        return Result.ok();
    }

    @PostMapping("save")
    @ApiOperation("保存")
    @LogOperation("保存用户")
    @RequiresPermissions("sys:user:save")
    public Result save(@Validated @RequestBody SysUserDTO dto) {
        sysUserService.save(dto);
        return Result.ok();
    }

    @PostMapping("update")
    @ApiOperation("修改")
    @LogOperation("修改用户")
    @RequiresPermissions("sys:user:update")
    public Result update(@Validated(UpdateGroup.class) @RequestBody SysUserDTO dto) {
        sysUserService.update(dto);
        return Result.ok();
    }

    @PostMapping("delete")
    @ApiOperation("删除")
    @LogOperation("删除用户")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@Validated @RequestBody Integer[] ids) {
        sysUserService.delete(Arrays.asList(ids));
        return Result.ok();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出用户")
    @RequiresPermissions("sys:user:export")
    public void export(@RequestParam HashMap<String, Object> params, HttpServletResponse response) {
        String filename = "export_" + System.currentTimeMillis();
        //List<SysUserExcel> list = sysUserService.exportList(params);
        //EasyExcelUtil.simpleWrite(response, filename, list, "用户数据", SysUserExcel.class);

        EasyExcelUtil.repeatWrite(response, filename, "", SysUserExcel.class, new EasyExcelRepeatWritePages<SysUserExcel>() {
            final int pageSize = 1000;
            @Override
            public int getPageSize() {
                return (int) Math.ceil(sysUserService.count(params) * 1.0 / pageSize);
            }

            @Override
            public List<SysUserExcel> getCurrentPageData(int page) {
                //hashmap转成dto，service少写一个方法
                SysUserQueryDTO dto =
                        BeanUtil.fillBeanWithMap(params, new SysUserQueryDTO(), true, true);
                dto.setPage(page);
                dto.setPageSize(pageSize);
                Page<SysUserVO> data = sysUserService.page(dto);

                return ConvertUtil.sourceToTarget(data.getRecords(), SysUserExcel.class);
            }
        });
    }
}